package com.itheima.reggie.service.Impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.util.StringUtils;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        Employee employee=employeeMapper.findByName(username);
        if (employee==null){
            return ResultInfo.error("账户名不存在");
        }

        String md5password = SecureUtil.md5(password);
        if (!StringUtils.equals(md5password,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        if (employee.getStatus()!=Employee.STATUS_ENABLE){
            return ResultInfo.error("当前账户未激活");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> find(String name) {
        return employeeMapper.find(name);
    }

    @Override
    public void save(Employee employee) {
        employee.setId(IdUtil.getSnowflake(1,1).nextId());

        String password = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(password);

        employee.setStatus(Employee.STATUS_ENABLE);

//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);

        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        Employee employee=employeeMapper.findById(id);
        return employee;
    }

    @Override
    public void update(Employee employee) {
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);
        employeeMapper.update(employee);
    }
}
